package com.amado.course42Nio.demo2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 0:00
 */
public class NioServer {
    private Selector selector;
    public static void main(String[] args) throws IOException {
        NioServer nioServer = new NioServer();
        nioServer.go();
    }

    NioServer() throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();
        //默认是true,false不堵塞
        channel.configureBlocking(false);
        ServerSocket socket = channel.socket();
        socket.bind(new InetSocketAddress(8080));
        selector = Selector.open();
        // 绑定channel的accept
        channel.register(selector, SelectionKey.OP_ACCEPT);
    }

    private void go() throws IOException {
        while (selector.select() > 0) {
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    accept(selectionKey);
                } else if (selectionKey.isReadable()) {
                    read(selectionKey);
                } else if (selectionKey.isWritable()) {
                    doWrite(selectionKey);
                }
            }
        }
    }

    private void accept(SelectionKey selectionKey) throws IOException {
        ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
        SocketChannel socketChannel = server.accept();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector,SelectionKey.OP_READ,new Buffers(1024,1024));
        System.out.println("acceptable");
    }
    private void read(SelectionKey selectionKey) throws IOException {
        Buffers buffers = (Buffers)selectionKey.attachment();
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer readBuffer = buffers.getReadBuffer();
        ByteBuffer writeBuffer = buffers.getWriteBuffer();
        socketChannel.read(readBuffer);
        readBuffer.flip();
        CharBuffer charBuffer = Charset.forName("UTF-8").decode(readBuffer);
        System.out.println("接收到数据 " + charBuffer.array());
        System.out.println("接收到数据 " + new String(charBuffer.array()));
        //重新读取
        readBuffer.rewind();
        writeBuffer.put("echo from client".getBytes("UTF-8"));
        writeBuffer.put(readBuffer);

        readBuffer.clear();
        //设置通道写事件
        selectionKey.interestOps(SelectionKey.OP_WRITE);
    }
    private void doWrite(SelectionKey selectionKey) throws IOException {
        Buffers buffers = (Buffers)selectionKey.attachment();
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer writeBuffer = buffers.getWriteBuffer();
        //开始写
        writeBuffer.flip();
        int len = 0;
        while(writeBuffer.hasRemaining()) {
            len = channel.write(writeBuffer);
            if(len==0){
                break;
            }
        }
        //压缩此缓冲区
        writeBuffer.compact();
        ////&～xx 代表取消事件
        selectionKey.interestOps(selectionKey.interestOps() & (~SelectionKey.OP_WRITE));
    }
}
